function [fdata_x, fdata_y, Gmax, a, v05, Gleak, Vleak, error] = CCIV_fit(x_data, y_data, lam, pmask, params, maxiter)
% activation parameter fitting
% try single boltzmann fit  I=Gmax*(V-Vr)/(1+exp(-a*alpah*(V-V0.5))) + Gleak((V-Vleak);
% Fits directly to current-voltage relationship from current clamp.
% 1/6/99 P. Manis

model=45;	%single boltzman plus leak, inverted format 
alpha=(10^-3)*9.648*10^4/(8.3143*(273.16+params(2)));	%1/25mV  =F/RT
FitData(:,1)=x_data';
FitData(:,2)=(y_data)';

%parameters: imax     z       V0.5 
initpar = lam;
m=max(y_data);
%            gmax      z     Vhalf   gleak     vleak
lbound =  [-1000,    -20,     -80,       0,     -100];
ubound =  [ 1000,     20,      20,     500,       50];
order=length(initpar);

beta = params(1);

[error,lam]=curve_fitting(FitData(:,1), FitData(:,2), 'levenberg','cubic', model, order, initpar,...
   pmask, lbound, ubound, alpha, beta, maxiter);

%now plot it
x = FitData(:,1); 
z = FitData(:,2);
% f=z-(lam(1).*(x-Vr)/(1+exp((x-lam(3)).*lam(2)*alpha))+lam(4).*(x-lam(5)));
fdata_x=min(x):2:max(x);

%calculate more values, so the fit data looks better
fdata_y=((lam(1).*(fdata_x-beta))./(1+exp(-(fdata_x-lam(3))*(lam(2)*alpha))))+(lam(4).*(fdata_x-lam(5)));
% store results
Gmax=lam(1); a=lam(2); v05=lam(3); Gleak=lam(4); Vleak=lam(5);
%disp(sprintf('Gmax: %8.3f  a: %8.3f  V05: %8.3f  Gleak: %8.3f  Vleak: %8.3f', ...
%   Gmax, a, v05, Gleak, Vleak))
